<?php


namespace app\controllers;


use app\components\AppController;
use app\models\Book;
use app\models\Comment;
use app\models\User;
use app\models\UserFavorite;
use app\models\UserHistory;
use app\models\UserScore;
use Throwable;
use Yii;
use yii\db\Exception;
use yii\db\StaleObjectException;
use yii\filters\AccessControl;
use yii\web\NotFoundHttpException;

class UserController extends AppController {

    /**
     * @var User
     */
    public $user;

    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    ['allow' => TRUE, 'roles' => ['@']]
                ]
            ]
        ];
    }

    public function actionIndex() {
        $this->view->title = '用户中心';
        return $this->render([], '/user');
    }

    public function actionDeleteAllHistory() {
        return UserHistory::deleteAllHistory();
    }

    /**
     * @return array|false|int
     */
    public function actionDeleteAllFavorite() {
        return UserFavorite::deleteAllFavorite();
    }

    public function actionLogout() {
        Yii::$app->user->logout();
        return Yii::$app->getResponse()->redirect(['/']);
    }

    /**
     * @return array
     * @throws NotFoundHttpException
     * @throws Exception
     */
    public function actionSaveScore() {
        $id = intval($this->get('id'));
        $score = intval($this->get('score'));

        $model = Book::findOne($id);
        if (!$model) {
            throw new NotFoundHttpException('漫画未找到');
        }

        return UserScore::saveScore($score, $model);
    }

    /**
     * @return array
     * @throws Exception
     * @throws NotFoundHttpException
     * @throws Throwable
     */
    public function actionSaveFavorite() {
        $id = intval($this->get('id'));
        $model = Book::findOne($id);
        if (!$model) {
            throw new NotFoundHttpException('漫画未找到');
        }
        return UserFavorite::saveFavorite($id);
    }

    /**
     * @throws Exception
     */
    public function actionComment() {
        if (!$this->isPost()) {
            return $this->error();
        }

        $model = new Comment();
        $model->uid = Yii::$app->user->id;
        $model->type = Comment::TYPE_BOOK;
        $model->content = $this->post('content');
        $model->book_id = $this->post('book_id');
        $model->status = Comment::YES;
        return $model->save();
    }
}